package com.szlanyou.thirdsdk.retrofit.interceptor;
import com.google.gson.Gson;
import com.szlanyou.thirdsdk.retrofit.client.ClientCommonParamsManager;
import com.szlanyou.thirdsdk.retrofit.util.MyLogUtil;
import com.szlanyou.thirdsdk.retrofit.util.RequestBodyUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author  :陈章
 * func:
 * 拦截添加HttpClient的POST请求公共参数
 * 2021.7.19 Deprecated:改在单次请求里实现
 */
@Deprecated
public class PostMethodParamAddInterceptor implements Interceptor {
    private static final String TAG = "PostMethodParamAddInterceptor";

    private Map<String, Object> paramsMap;
    private final Gson gson;
    private ClientCommonParamsManager clientCommonParamsManager;

    public PostMethodParamAddInterceptor(ClientCommonParamsManager clientCommonParamsManager) {
        this.clientCommonParamsManager = clientCommonParamsManager;
        gson = new Gson();
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request orgRequest = chain.request();
        String method = orgRequest.method();
        if(method.equalsIgnoreCase(ShareInfoHelper.METHOD_POST)){
            paramsMap = clientCommonParamsManager.getCommonParams();
            RequestBody body = orgRequest.body();
            //收集请求参数，方便调试
            Map  bodyJsonMap = new HashMap<>();
            if (body != null) {

                RequestBody newBody = null;

                if (body instanceof FormBody) {
                    newBody = addParamsToFormBody((FormBody) body, bodyJsonMap);
                } else if (body instanceof MultipartBody) {
                    newBody = addParamsToMultipartBody((MultipartBody) body, bodyJsonMap);
                }else if(body instanceof RequestBody){
                    newBody = fillParamsToRequestBody(body,bodyJsonMap);
                }

                if (null != newBody) {
                    ClientCommonParamsManager.OnRequestBodyInterceptListener onHeaderInterceptListener = clientCommonParamsManager.getOnRequestBodyInterceptListener();
                    if(onHeaderInterceptListener != null){
                        onHeaderInterceptListener.onRequestBodyIntercept(gson.toJson(bodyJsonMap));
                    }
                    Request newRequest = orgRequest.newBuilder()
                            .url(orgRequest.url())
                            .method(method, newBody)
                            .build();

                    return chain.proceed(newRequest);
                }
            }
        }

        return chain.proceed(orgRequest);
    }

    private RequestBody fillParamsToRequestBody(RequestBody originRequestBody,Map  bodyJsonMap) {
        Set<Map.Entry<String,Object>> keySet = paramsMap.entrySet();
        StringBuilder commonParamsLogInfo = new StringBuilder();
        commonParamsLogInfo.append("公共请求参数\n");
        for (Iterator<Map.Entry<String,Object>> it = keySet.iterator();it.hasNext();) {
            Map.Entry<String, Object> item = it.next();
            String key = item.getKey();
            Object value = item.getValue();
            commonParamsLogInfo.append(String.format("key = %s,value = %s\n",key,value));
        }
        if(paramsMap.size() > 0){
            MyLogUtil.d(TAG,commonParamsLogInfo.toString());
        }

        bodyJsonMap.putAll(paramsMap);

        //添加原请求体
        Map mapFromRequestBody = RequestBodyUtil.getMapFromRequestBody(originRequestBody);
        bodyJsonMap.putAll(mapFromRequestBody);
        //OkHttp 4.0写法
        return RequestBody.create(gson.toJson(bodyJsonMap), MediaType.parse("application/json; charset=utf-8"));
//        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"),gson.toJson(bodyJsonMap));
    }

    /**
     * 为MultipartBody类型请求体添加参数
     *
     * @param body
     * @param bodyJsonMap
     * @return
     */
    private MultipartBody addParamsToMultipartBody(MultipartBody body, Map<String,String> bodyJsonMap) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        Set<Map.Entry<String,Object>> keySet = paramsMap.entrySet();
        StringBuilder commonParamsLogInfo = new StringBuilder();
        commonParamsLogInfo.append("公共请求参数\n");
        for (Iterator<Map.Entry<String,Object>> it = keySet.iterator();it.hasNext();) {
            Map.Entry<String, Object> item = it.next();
            String key = item.getKey();
            Object value = item.getValue();
            commonParamsLogInfo.append(String.format("key = %s,value = %s\n",key,value));
            builder.addFormDataPart(key, String.valueOf(value));
            bodyJsonMap.put(key, String.valueOf(value));
        }
        if(paramsMap.size() > 0){
            MyLogUtil.d(TAG,commonParamsLogInfo.toString());
        }

        //添加原请求体
        for (int i = 0; i < body.size(); i++) {
            builder.addPart(body.part(i));
        }
        return builder.build();
    }

    /**
     * 为FormBody类型请求体添加参数
     *
     * @param body
     * @param bodyJsonMap   用于汇总body及公共请求参数map的json
     * @return
     */
    private FormBody addParamsToFormBody(FormBody body, Map<String,String> bodyJsonMap) {
        FormBody.Builder builder = new FormBody.Builder();
        StringBuilder commonParamsLogInfo = new StringBuilder();
        commonParamsLogInfo.append("公共请求参数\n");
        Set<Map.Entry<String,Object>> keySet = paramsMap.entrySet();
        for (Iterator<Map.Entry<String,Object>> it = keySet.iterator();it.hasNext();) {
            Map.Entry<String, Object> item = it.next();
            String key = item.getKey();
            Object value = item.getValue();
            commonParamsLogInfo.append(String.format("key = %s,value = %s\n",key,value));
            builder.add(key, String.valueOf(value));
            bodyJsonMap.put(key, String.valueOf(value));
        }
        if(paramsMap.size() > 0){
            MyLogUtil.d(TAG,commonParamsLogInfo.toString());
        }

        //添加原请求体
        for (int i = 0; i < body.size(); i++) {
            builder.addEncoded(body.encodedName(i), body.encodedValue(i));
            bodyJsonMap.put(body.name(i), body.value(i));
        }

        return builder.build();
    }

}